﻿using System;
using nRoute.Components;
using nRoute.Samples.ExtendedMVVM.Views;
using nRoute.ViewModels;
using nRoute.Components.Composition;
using nRoute.Samples.ExtendedMVVM.Services;

namespace nRoute.Samples.ExtendedMVVM.ViewModels
{
    [MapViewModel(typeof(PageD))]
    public class PageDViewModel
        : ViewModelBase
    {
        private const string STORE_KEY = "PageD_DATA";

        private string _text;
        private bool _isDirty;
        private ILocalStoreService _storeService;

        [ResolveConstructor]
        public PageDViewModel(ILocalStoreService storeService)
        {
            _storeService = storeService;
            LoadStoredText();
            SetupCommands();
        }

#region Properties

        public ActionCommand SaveTextCommand { get; private set; }

        public string Text
        {
            get { return _text; }
            set
            {
                if (!string.Equals(_text, value, StringComparison.InvariantCulture))
                {
                    _text = value;
                    _isDirty = true;
                    NotifyPropertyChanged(() => Text);
                }
            }
        }

#endregion

#region Helpers

        private void LoadStoredText()
        {
            this.Text = _storeService.Load(STORE_KEY);
            _isDirty = false;
        }

        private void SetupCommands()
        {
            SaveTextCommand = new ActionCommand(() =>
            {
                _storeService.Save(STORE_KEY, this.Text);
                _isDirty = false;
            }, 
            () => _isDirty)            
            .RequeryOnPropertyChanged(this, () => Text)
            .RequeryWhenExecuted();
        }

#endregion

    }
}
